const mysql = require('mysql2/promise');
require('dotenv').config();
let options = {
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
};
console.log(options);
const pool = mysql.createPool(options);

// 一个用于执行查询的函数
async function query(sql, params) {
    const connection = await pool.getConnection();
    try {
        const [rows, fields] = await connection.execute(sql, params);
        return rows;
    } catch (error) {
        throw error;
    } finally {
        connection.release();
    }
}

const getUserById = async (id) => {
    const [rows] = await query('SELECT * FROM users WHERE id = ?', [id]);
    return rows[0];
};

async function getUserByEmail(email) {
    try {
        const [result] = await query('SELECT * FROM users where email = ?', [email]);
        console.log("-------getUserByEmail result", result);
        return result;
    } catch (err) {
        console.log("---------err", err);
    }
};

const createUser = async (user) => {
    const { username, email, password } = user;
    try {
        const result = await query('INSERT INTO users (username, email, password) VALUES (?, ?, ?)', [username, email, password]);
        console.log("---------createUser result", result);
        return { id: result.insertId, ...user };
    } catch (err) {
        console.log("---------err", err);
    }


};

module.exports = { getUserById, getUserByEmail, createUser };